//
// Created by maicss on 22-4-18.
//

#include "MainWindow.h"
#include <QVBoxLayout>
#include <QIntValidator>
#include <QDebug>
#include "qrcode/qrcodegen.hpp"
#include <QNetworkInterface>
#include <QComboBox>
#include <QDesktopServices>

using namespace std;
using namespace qrcodegen;
MainWindow::MainWindow() {
    initUI();
    updateNetworks();
    stopServer();
    isOpen = false;
}

void MainWindow::mousePressEvent(QMouseEvent *event) {
    QWidget::mousePressEvent(event);
    m_isDrag = true;
    m_mousePoint = event->globalPos();
    m_windowPoint = frameGeometry().topLeft();
}

void MainWindow::mouseMoveEvent(QMouseEvent *event) {
    QWidget::mouseMoveEvent(event);
    if (m_isDrag){
        auto offset = event->globalPos() - m_mousePoint;
        move(m_windowPoint+offset);
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event) {
    QWidget::mouseReleaseEvent(event);
    m_isDrag = false;
}

void MainWindow::setPath(const QString& path) {
    m_pathshow.setText("共享目录："+path);
}

QImage MainWindow::setQRCode(const QString& context) {
    QrCode qr = QrCode::encodeText(context.toUtf8(), QrCode::Ecc::MEDIUM);
    int pointSize = 150/qr.getSize();
    QImage image(pointSize*qr.getSize(),pointSize*qr.getSize(),QImage::Format_ARGB32);
    for (int y = 0; y < qr.getSize(); y++) {
        for (int x = 0; x < qr.getSize(); x++) {
            for (int i = x*pointSize; i < (x+1)*pointSize; ++i) {
                for (int j = y*pointSize; j < (y+1)*pointSize; ++j) {
                    if(qr.getModule(x, y)){
                        image.setPixelColor(i,j,QColor("#000000"));
                    }else {
                        image.setPixelColor(i,j,QColor(0,0,0,0));
                    }
                }
            }
        }
    }
    m_qrcodeshow.setPixmap(QPixmap::fromImage(image));
    return image;
}

void MainWindow::initUI() {
    setFixedSize(345,440);
    setWindowFlags(Qt::FramelessWindowHint);
    setStyleSheet("QMainWindow {"
                  "border: 2px solid #0B64FF;"
                  "background-color: #FFFFFF;"
                  "}"
                  "QCheckBox{"
                  "margin: 0 100px;"
                  "}");
    m_isDrag = false;

    setCentralWidget(&m_stk);
    m_stk.addWidget(&m_page_show);
    auto layout = new QVBoxLayout;
    layout->addWidget(&titleBar);
    m_pathshow.setStyleSheet("QLabel {"
                             "color: #757575;"
                             "}");
    m_pathshow.setAlignment(Qt::AlignCenter);
    layout->addWidget(&m_pathshow);
    m_pathshow.setFixedHeight(28);
    setPath("/home/maicss");

    layout->addWidget(&m_qrcodeshow);
    m_qrcodeshow.setAlignment(Qt::AlignCenter);
    setQRCode("https://www.baidu.com");
    auto port_layout = new QHBoxLayout;
    port_layout->addStretch();
    port_layout->addWidget(&m_lineEdit);
    port_layout->addWidget(&m_comboBox);
    m_comboBox.hide();
    port_layout->addStretch();
    layout->addSpacing(12);
    layout->addLayout(port_layout);
    QRegExp regExp("/^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|(^[1-5][0-9][0-9][0-9][0-9]$)|(^6[0-5][0-5][0-3][0-5]$)/");//端口号匹配正则
    auto *pattern= new QRegExpValidator(regExp, this);
    m_lineEdit.setValidator(pattern);
    m_lineEdit.setPlaceholderText("端口号");
    m_lineEdit.setFixedSize(200,30);
    m_lineEdit.setStyleSheet("QLineEdit {"
                             "border: 2px solid #EEEEEE;"
                             "border-radius: 12px;"
                             "}");
    m_lineEdit.setAlignment(Qt::AlignCenter);
    m_lineEdit.setText("8080");
    m_comboBox.setFixedSize(200,30);
    m_comboBox.setStyleSheet("QComboBox {"
                             "border: 2px solid #EEEEEE;"
                             "border-radius: 12px;"
                             "}");

    layout->addWidget(&m_allowUpload);
    layout->addWidget(&m_allowDownloadFolder);
    layout->addWidget(&m_tip);
    m_tip.setAlignment(Qt::AlignCenter);
    m_tip.hide();
    m_allowUpload.setText("允许上传文件");
    m_allowDownloadFolder.setText("允许下载文件夹");


    auto btn_layout = new QHBoxLayout;
    btn_layout->addStretch();
    btn_layout->addWidget(&m_btn_openServer);
    btn_layout->addStretch();
    layout->addLayout(btn_layout);
    m_btn_openServer.setText("启动服务");
    m_btn_openServer.setFixedSize(165,40);
    m_btn_openServer.setFont(QFont("",12));
    m_btn_openServer.setStyleSheet("QPushButton {"
                                   "background-color: #0B64FF;"
                                   "color: #FFFFFF;"
                                   "border-radius: 20px;"
                                   "border: 1px solid #FFF"
                                   "}"
                                   "QPushButton::hover {"
                                   "background-color: #3B82FF;"
                                   "}");
    layout->addSpacing(18);
    layout->setAlignment(Qt::AlignHCenter);
    m_page_show.setLayout(layout);
    connect(&m_btn_openServer,&QPushButton::clicked,this,&MainWindow::startServer);

    connect(&m_comboBox,&QComboBox::currentTextChanged,this, [=](){
        Network network = networks.at(m_comboBox.currentData().toInt());
        QString url = "http://"+network.ip+":"+m_lineEdit.text();
        setQRCode(url);
//        m_tip.setText("您可以使用移动设备扫码或者访问：\n<a href=\""+url+"\">"+url+"</a>");
        m_tip.setText("<p>您可以使用移动设备扫码或者访问：</p><a href="+url+">"+url+    "</a>");
    });

    connect(&m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [=](int exitCode, QProcess::ExitStatus exitStatus){
        stopServer();
    });
    connect(&m_tip,&QLabel::linkActivated,this,&MainWindow::openUrl);
}

void MainWindow::startServer() {
    updateNetworks();
    if (isOpen){
        stopServer();
        return;
    }
    m_process.setProgram("/usr/bin/foldershare");
    QStringList args;
    m_path="/home/maicss";
    args<<m_path;
    if(m_allowUpload.isChecked()){
        args<<"-u";
    }

    if(m_allowDownloadFolder.isChecked()){
        args<<"-f";
    }
    args<<"-p"<<m_lineEdit.text();
    m_process.setArguments(args);
    m_process.start();
    m_process.waitForStarted();
    m_btn_openServer.setText("关闭服务");
    m_comboBox.show();
    m_lineEdit.hide();
    m_allowDownloadFolder.hide();
    m_allowUpload.hide();
    isOpen = true;
    m_tip.show();
}

void MainWindow::stopServer() {
    isOpen = false;
    m_btn_openServer.setText("启动服务");
    m_comboBox.hide();
    m_lineEdit.show();
    m_process.kill();
    m_allowDownloadFolder.show();
    m_allowUpload.show();
    m_tip.hide();
    setQRCode("请您先启动服务");
}

MainWindow::~MainWindow() {
    stopServer();
}

void MainWindow::updateNetworks() {
    int i=0, j=0, x=0;
    m_comboBox.clear();
    networks.clear();
    QList<QNetworkInterface> networkInterface = QNetworkInterface::allInterfaces();
    for (QList<QNetworkInterface>::const_iterator it = networkInterface.constBegin(); it != networkInterface.constEnd(); ++it)
    {
        //获取连接地址列表
        QList<QNetworkAddressEntry> addressEntriesList = (*it).addressEntries();
        for (QList<QNetworkAddressEntry>::const_iterator jIt = addressEntriesList.constBegin(); jIt != addressEntriesList.constEnd(); ++jIt)
        {
            if ((*jIt).ip().protocol() == QAbstractSocket::IPv4Protocol && (*jIt).ip() !=  QHostAddress(QHostAddress::LocalHost)){
                Network network;
                network.name = (*it).name();
                network.ip = (*jIt).ip().toString();
                networks.append(network);
                m_comboBox.addItem(network.name+": "+network.ip,QVariant(x));
                x++;
            }
            j ++;
        }
        i ++;
    }
}
void MainWindow::openUrl(QString url)
{
    QDesktopServices::openUrl(QUrl(url));
}
